package com.lly.songhigh.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.lly.songhigh.R;
import com.lly.songhigh.entity.dao.RecentSearch;

import java.util.List;

/**
 * Created by 李新伟 on 15/11/7.
 * 最近搜索的适配器
 */
public class RecentSearchAdapter extends BaseAdapter {
    private List<RecentSearch> recentSearches;
    private Context context;
    private OnItemDeleteListener onItemDeleteListener;

    public RecentSearchAdapter(List<RecentSearch> recentSearches, Context context) {
        this.recentSearches = recentSearches;
        this.context = context;
    }

    public void deleteByPosition(int position) {
        recentSearches.remove(position);
        notifyDataSetChanged();
    }

    public void deleteAll(){
        recentSearches = null;
        notifyDataSetChanged();
    }

    public void setOnItemDeleteListener(OnItemDeleteListener onItemDeleteListener) {
        this.onItemDeleteListener = onItemDeleteListener;
    }

    public interface OnItemDeleteListener{
        void onClickDelete(RecentSearch recentSearch, int position);
    }
    @Override
    public int getCount() {
        return recentSearches != null && recentSearches.size() > 0 ? recentSearches.size() : 0;
    }

    @Override
    public RecentSearch getItem(int position) {
        return recentSearches.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.recent_search_item, null);
            viewHolder = new ViewHolder();
            viewHolder.recentSearchItemTv = (TextView) convertView.findViewById(R.id.recent_search_item_tv);
            viewHolder.recentSearchItemDel = (ImageView) convertView.findViewById(R.id.recent_search_item_del);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        RecentSearch recentSearch = getItem(position);
        viewHolder.recentSearchItemTv.setText(recentSearch.getSearchTv());
        viewHolder.recentSearchItemDel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onItemDeleteListener != null) {
                    onItemDeleteListener.onClickDelete(recentSearches.get(position), position);
                }
            }
        });
        return convertView;
    }

    private class ViewHolder{
        private TextView recentSearchItemTv;
        private ImageView recentSearchItemDel;
    }
}
